<template>
	<div>
		<a-modal title="退库" :width="1200" :visible="visible" :maskClosable="false" :confirmLoading="confirmLoading"
			@ok="handleSubmit" @cancel="handleCancel">
			<a-card :bordered="false">
				<div class="table-page-search-wrapper">
					<a-form-model ref="ruleForm" :model="form" :rules="rules" layout="inline">
						<a-form-model-item label="退库原因" prop="reason">
							<a-input class="w-full" :maxLength="200" v-model="form.reason" placeholder="请输入" />
						</a-form-model-item>
					</a-form-model>
				</div>


				<s-table ref="table" size="default" :columns="columns" :data="getData" :alert="true" :scroll="{
					x: 1800
				}" :showPagination="false" :rowKey="record => record.orderId + record.orderMaterialId">
					<span slot="materialModelNumber" slot-scope="text, record">
						{{ record.material ? record.material.materialModelNumber : '' }}
					</span>
					<!-- <span slot="image" slot-scope="text">
						<image-preview :images="text" />
					</span> -->
					<span slot="image" slot-scope="text,record">
						<image-preview1 :images="text" :imageUrl="record.material.imageUrl" />
					</span>
					<template slot="normalReturnNumber" slot-scope="text, record">
						<a-input-number
							:disabled="record.extraNumber > 0 || ((record.number - record.returnNumber - (record.returnStockNumber + record.extraReturnStockNumber) <= 0))"
							v-model:value="record.normalReturnNumber" :min="0"
							:max="record.number - record.returnNumber - (record.returnStockNumber + record.extraReturnStockNumber)"
							placeholder="请输入" style="width: 67px;" />
					</template>
					<template slot="customExtraNumber" slot-scope="text, record">
						<a-input-number
							:disabled="record.number > 0 || ((record.extraNumber - record.extraReturnNumber - (record.returnStockNumber + record.extraReturnStockNumber)) <= 0)"
							v-model:value="record.customExtraNumber" :min="0"
							:max="record.extraNumber - record.extraReturnNumber - (record.returnStockNumber + record.extraReturnStockNumber)"
							placeholder="请输入" style="width: 67px;" />
					</template>


				</s-table>


			</a-card>
		</a-modal>

	</div>
</template>

<script lang="ts">
import { Component, Vue, Ref, Prop, Emit } from "vue-property-decorator";
import { STable } from '@/components'
import { emsPlanOrderAdd, page } from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import { debounce } from 'xijs';

type Record = {
	materialId: string,
	materialCode: string,
	materialName: string,
	number: number,
	returnNumber: number,
	ckTotalNumber: number,
	ckTotalExtraNumber: number,
	completedNumber: number,
	totalNumber: number,
	returnStockNumber: number,
	extraReturnStockNumber: number,
	extraReturnNumber: number,
	useNumber: number,
	extraNumber: number,
	productRecord: any
}


@Component({
	components: {
		STable,
	}
})

export default class ProductionBackStoreEditForm extends Vue {
	@Ref() readonly table!: any
	@Ref() readonly ruleForm!: any

	@Prop({ required: true }) sourceOrderId: string

	@Emit()
	handleOk() {

	}

	visible = false
	title = ''
	form = {
		orderId: '',
		reason: '',
	}
	rules = {
		reason: [
			{ required: true, message: '请输入退库原因', trigger: 'blur' },
		],
	}
	// 查询参数
	queryParam = {
		materialType: '',
		orderId: '',
		pageSize: 10
	}

	columns = [
		{
			align: 'center',
			title: '序号', width: '80px',
			dataIndex: '',
			customRender(text: any, record: Record, index: number) {
				return `${index + 1}`
			}
		},
		{
			align: 'center',
			title: '出库单号',
			dataIndex: 'orderNumber'
		},
		{
			align: 'center',
			title: '创建时间',
			dataIndex: 'createTime'
		},
		{
			align: 'center',
			title: '产品',
			dataIndex: 'productName',
		},
		{
			align: 'center',
			title: 'BOM',
			dataIndex: 'bomName',
			customRender: (text, record, index) => record.bomName || '/',

		},
		{
			align: 'center',
			title: '物料',
			dataIndex: 'materialName'
		},
		{
			align: 'center',
			title: '规格',
			dataIndex: 'materialModelNumber',
			scopedSlots: { customRender: 'materialModelNumber' }
		},
		{
			align: 'center',
			title: '图片',
			dataIndex: 'image',
			scopedSlots: { customRender: 'image' }
		},
		{
			align: 'center',
			title: '物料编码',
			dataIndex: 'materialCode'
		},

		{
			align: 'center',
			title: '总数量',
			dataIndex: 'totalNumber'
		},
		{
			align: 'center',
			title: '已正常出库数量',
			dataIndex: '',
			customRender: (text: any, record: Record,) => {
				if (record.extraNumber > 0) {
					return '/'
				}

				return record.ckTotalNumber - record.ckTotalExtraNumber
			}
		},
		{
			align: 'center',
			title: '正常剩余可退库数量',
			dataIndex: '',
			customRender(text: any, record: Record,) {
				if (record.extraNumber > 0) {
					return '/'
				}
				let number = record.ckTotalNumber - record.ckTotalExtraNumber
				return `${number - record.useNumber - record.productRecord.returnNumber}`
			}
		},
		{
			align: 'center',
			title: '已额外出库数量',
			dataIndex: '',
			customRender: (text: any, record: Record,) => {
				if (record.number > 0) {
					return '/'
				}
				return record.ckTotalExtraNumber
			}
		}, {
			align: 'center',
			title: '额外剩余可退库数量',
			dataIndex: '',
			customRender(text: any, record: Record) {
				if (record.number > 0) {
					return '/'
				}
				return `${record.ckTotalExtraNumber - record.productRecord.extraReturnNumber}`
			}
		},
		{
			align: 'center',
			title: '本次出库数量',
			dataIndex: '',
			customRender: (text: any, record: Record,) => record.number > 0 ? record.number : record.extraNumber
		},
		{
			align: 'center',
			title: '已退库数量',
			dataIndex: '',
			customRender(text: any, record: Record,) {
				return `${record.returnStockNumber + record.extraReturnStockNumber}`
			}
		}, {
			align: 'center',
			title: '待确认退库数量',
			dataIndex: '',
			customRender: (text: any, record: Record,) => record.number > 0 ? record.returnNumber : record.extraReturnNumber
		}, {
			align: 'center',
			title: '剩余未退库数量',
			dataIndex: '',
			customRender(text: any, record: Record,) {
				let number = record.number > 0 ? record.number : record.extraNumber
				let returnNumber = record.number > 0 ? record.returnNumber : record.extraReturnNumber
				return `${number - returnNumber - (record.returnStockNumber + record.extraReturnStockNumber)}`
			}
		},
		{
			align: 'center',
			title: '本次正常退库数量',
			dataIndex: '',
			scopedSlots: { customRender: 'normalReturnNumber' }
		}, {
			align: 'center',
			title: '本次额外退库数量',
			dataIndex: '',
			scopedSlots: { customRender: 'customExtraNumber' }
		},
	]


	orderMaterialIds: string[] = []
	selectedRowKeys: string[] = []
	selectedRows: Record[] = []

	confirmLoading = false
	emsOrder = null

	get routePath() {
		let urlParam = this.$util.getUrlParam(this.$route.path)
		return urlParam
	}

	get materialType() {
		return this.routePath?.materialType || this.$businessEnum.MATERIAL_TYPE_ENUM.material.id
	}


	// 加载数据方法 必须为 Promise 对象
	getData(parameter: { pageNo: number, pageSize: number }) {
		const params = {
			...parameter,
			sourceOrderMaterialIdList: this.orderMaterialIds,
			pageSize: -1
		}
		return page(params).then((res) => {
			return res.data
		})
	}

	show(orderMaterialIds: string[]) {
		this.visible = true
		this.orderMaterialIds = orderMaterialIds
		setTimeout(() => {
			this.table.refresh()
		}, 100)
	}


	handleSubmit = debounce(this.submit, 1000)

	submit() {
		this.ruleForm?.validate(valid => {
			if (valid) {
				let orderMaterials = this.table?.$data?.localDataSource?.filter(item => item.normalReturnNumber > 0 || item.customExtraNumber > 0)?.map(value => {
					return {
						orderMaterialId: value.orderMaterialId,
						extraNumber: value.customExtraNumber || 0,
						returnNumber: value.normalReturnNumber || 0,
					}
				})


				if (!orderMaterials.some(item => item.returnNumber > 0) && !orderMaterials.some(item => item.extraNumber > 0)) {
					return this.$message.info('请输入退库数量')
				}

				let params = {
					// 订单类型 1退库 2返执行
					orderType: 1,
					materialType: this.materialType,
					sourceOrderId: this.sourceOrderId,
					reason: this.form.reason,
					materialReturnNumberList: orderMaterials,
				}
				emsPlanOrderAdd(params).then(res => {
					//@ts-ignore
					if (res.success) {
						this.$message.info('退库成功')
						this.handleOk()
						this.handleCancel()
					} else {
						//@ts-ignore
						this.$message.error('退库失败：' + res.message)
					}
				})
			} else {
				console.log('error submit!!');
				return false;
			}
		});

	}

	handleCancel() {
		this.visible = false;
		this.ruleForm?.resetFields()
	}

}
</script>

<style lang="less">
/deep/ .ant-form-item {
	display: flex !important;

	.ant-form-item-control-wrapper {
		flex: 1;
	}
}

button {
	margin-right: 8px;
}
</style>
